<!--
 * @Descripttion: 会员列表
 * @Author: xiao li
 * @Date: 2020-07-06 12:17:07
 * @LastEditors: xiao li
 * @LastEditTime: 2022-02-22 11:04:37
-->
<template>
  <div>
    <top-nav></top-nav>
    <div class="page-main">
      <div class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="searchForm"
        >
          <el-form-item label="输入查询" prop="name">
            <!-- ID/手机号/用户昵称 -->
            <el-input
              placeholder="用户ID/用户昵称"
              v-model="searchForm.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员等级" prop="level">
            <el-select
              v-model="searchForm.level"
              filterable
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in levelList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间查询" prop="range">
            <el-date-picker
              v-model="searchForm.range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="timestamp"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="储值查询" prop="">
            <el-input
              placeholder="请输入开始金额"
              v-model.number="searchForm.start_price"
              style="width: 138px"
            ></el-input>
            -
            <el-input
              placeholder="请输入结束金额"
              v-model.number="searchForm.end_price"
              style="width: 193px"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1)"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('searchForm')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" fixed> </el-table-column>
        <el-table-column prop="user_id" label="用户ID"> </el-table-column>
        <el-table-column prop="member_phone" label="手机号码">
        </el-table-column>
        <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
        <el-table-column prop="level_content" label="会员等级">
        </el-table-column>
        <el-table-column prop="order_num" label="订单总数量"> </el-table-column>
        <el-table-column prop="price" label="消费总金额"> </el-table-column>
        <el-table-column prop="integral" label="可用积分"> </el-table-column>
        <el-table-column prop="growth" label="当前成长值">
          <template slot-scope="scope">
            <div class="hover-class flex-center flex-column">
              <div class="flex-center">{{ scope.row.growth }}</div>
              <div
                @click="toShowDialog(scope.row, 'growth')"
                class="iconfont iconxiugai c-link f-paragraph mt-md"
              >
                修改
              </div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
                  prop="user_name"
                  label="累计成长值">
                </el-table-column> -->
        <el-table-column prop="stored" label="储值余额">
          <template slot-scope="scope">
            <div class="hover-class flex-center flex-column">
              <div class="flex-center">{{ scope.row.stored }}</div>
              <div
                @click="toShowDialog(scope.row, 'stored')"
                class="iconfont iconxiugai c-link f-paragraph mt-md mb-md"
              >
                修改
              </div>
              <div
                @click="toShowDialog(scope.row, 'record')"
                class="iconfont iconqianbao c-warning f-paragraph"
              >
                扣款
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="成为会员时间">
          <template slot-scope="scope">
            <p>{{ scope.row.create_time | handleTime(1) }}</p>
            <p>{{ scope.row.create_time | handleTime(2) }}</p>
          </template>
        </el-table-column>
        <el-table-column label="会员有效期">
          <template slot-scope="scope">
            <div
              v-if="scope.row.level_top === 999 && scope.row.over_time * 1 > 0"
            >
              <p>{{ scope.row.over_time | handleTime(1) }}</p>
              <p>{{ scope.row.over_time | handleTime(2) }}</p>
            </div>
            <div v-else>终生有效</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" width="100">
          <template slot-scope="scope">
            <div class="table-operate">
              <lb-button
                type="primary"
                size="mini"
                plain
                @click="
                  $router.push(`${appPath}/vip/detail?id=${scope.row.id}`)
                "
                >{{ $t('action.view') }}</lb-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      </lb-page>
    </div>

    <el-dialog
      title="修改成长值"
      :visible.sync="showDialog.growth"
      width="600px"
      center
      :before-close="beforeClose"
    >
      <div class="dialog-inner">
        <el-form
          @submit.native.prevent
          :model="dialogForm"
          ref="dialogForm"
          label-width="180px"
          class="basic-form"
        >
          <el-form-item label="成长值设置" prop="growth">
            <el-input
              :placeholder="`当前成长值 ${dialogForm.growth_old}`"
              v-model="dialogForm.growth"
              style="width: 300px"
            ></el-input>
            <lb-tool-tips
              >修改成长值会影响用户的会员等级，请慎重修改</lb-tool-tips
            >
          </el-form-item>
        </el-form>
        <div class="space-lg"></div>
        <div v-for="(item, index) in levelList" :key="index">
          <div
            class="flex-y-center f-caption"
            style="padding-left: 95px; line-height: 20px"
            v-if="index > 0"
          >
            <div>VIP{{ item.top }} {{ item.title }}</div>
            <div class="ml-lg">达成{{ item.growth }}</div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="toEditGrowthStored">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改储值余额"
      :visible.sync="showDialog.stored"
      width="600px"
      center
      :before-close="beforeClose"
    >
      <div class="dialog-inner">
        <el-form
          @submit.native.prevent
          :model="dialogForm"
          ref="dialogForm"
          label-width="180px"
          class="basic-form"
        >
          <el-form-item label="储值余额" prop="stored">
            <el-input
              :placeholder="`当前储值余额¥${dialogForm.stored_old}`"
              v-model="dialogForm.stored"
              style="width: 300px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="toEditGrowthStored">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="储值扣款"
      :visible.sync="showDialog.record"
      width="600px"
      center
      :before-close="beforeClose"
    >
      <div class="dialog-inner">
        <el-form
          @submit.native.prevent
          :model="dialogForm"
          ref="dialogForm"
          label-width="180px"
          class="basic-form"
        >
          <el-form-item label="会员手机号">
            <el-input
              :disabled="true"
              v-model="dialogForm.member_phone"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="会员等级">
            <el-input
              :disabled="true"
              v-model="dialogForm.level_content"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="储值余额">
            <el-input
              :disabled="true"
              v-model="dialogForm.stored"
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="消费金额">
            <el-input v-model="dialogForm.stored_price" style="width: 300px">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :rows="4"
              resize="none"
              maxlength="50"
              show-word-limit
              v-model="dialogForm.content"
              style="width: 300px"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="toStaffDeduction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      appPath: '',
      loading: false,
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        level: '',
        range: '',
        start_price: '',
        end_price: ''
      },
      levelList: [],
      tableData: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      page: 1,
      limit: 10,
      total: 0,
      showDialog: {
        growth: false,
        stored: false,
        record: false
      },
      dialogForm: {
        key: ''
      }
    }
  },
  created () {
    let { path } = this.$route
    this.appPath = path.includes('app/') ? '/app' : ''
  },
  activated () {
    this.getLevelList()
    this.getTableDataList()
  },
  methods: {
    async getLevelList () {
      let { code, data } = await this.$api.memberMemberLevelSelect()
      if (code !== 200) return
      let arr = [{
        id: 0,
        title: '全部'
      }]
      data.map(item => {
        arr.push(item)
      })
      this.levelList = arr
    },
    toResetForm () {
      this.$refs.multipleTable.clearSelection()
    },
    resetForm (name) {
      this.$refs[name].resetFields()
      this.searchForm.start_price = ''
      this.searchForm.end_price = ''
      this.getTableDataList(1)
    },
    getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      let { start_price: startPrice, end_price: endPrice } = this.searchForm
      if (!startPrice && endPrice) {
        this.$message.error('请输入开始金额')
        return
      }
      if (startPrice && !endPrice) {
        this.$message.error('请输入结束金额')
        return
      }
      if (startPrice * 1 > endPrice * 1) {
        this.$message.error('开始金额不能大于结束金额')
        return
      }
      this.loading = true
      let param = this.$util.pick(this.searchForm, [
        'page',
        'limit',
        'name',
        'level',
        'start_price',
        'end_price'
      ])
      let { range = '' } = this.searchForm
      if (range) {
        param.start_time = range[0] / 1000
        param.end_time = range[1] / 1000 + 24 * 3600 - 1
      }

      this.$api.memberMemberList(param).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      })
    },
    async updateUserLevel (id, status) {
      let { code } = await this.$api.memberMemberStatusUpdate({ id, status })
      if (code !== 200) {
        this.getTableDataList()
        return
      }
      this.$message.success(this.$t('tips.successOper'))
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    beforeClose () {
      for (let key in this.showDialog) {
        this.showDialog[key] = false
      }
      this.getTableDataList()
    },
    toShowDialog (item, key) {
      item.key = key
      item.growth_old = item.growth
      item.stored_old = item.stored
      this.dialogForm = item
      this.showDialog[key] = true
    },
    async toEditGrowthStored () {
      let { key, nickName, growth, stored } = this.dialogForm
      let word = key === 'growth' ? `成长值` : `储值余额`
      let number = key === 'growth' ? growth : stored
      let msg = ''
      if (key === 'growth') {
        if (!/^\+?[0-9]*$/.test(number)) {
          msg = '请输入非负整数'
        } else if (number * 1 < 1 || number * 1 > 9999998) {
          msg = '请输入大于0且小于9999999的整数'
        }
      }

      if (key === 'stored') {
        if (!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(number) || number < 0.01) {
          msg = '请输入大于0的数字，最多保留两位小数'
        }
      }
      if (msg) {
        this.$message.error(msg)
        return
      }
      this.$confirm(`是否确认修改用户 [${nickName}] 的${word}为 [${number}]，请再次确认操作！`, this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.toConfirmEdit(key)
      })
    },
    async toConfirmEdit () {
      let { key, id, user_id: uid, growth, stored } = this.dialogForm
      let methodModel = key === 'growth' ? 'memberUpdateGrowth' : 'memberStaffDeduction'
      let param = key === 'growth' ? { id, growth } : { id: uid, price: stored, content: '', type: 4 }
      let { code } = await this.$api[methodModel](param)
      if (code !== 200) return
      this.$message.success(this.$t('tips.successSub'))
      this.beforeClose()
    },
    async toStaffDeduction () {
      let { user_id: id, stored_price: price = 0, content = '', stored = 0 } = this.dialogForm
      let msg = ''
      if (!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(price) || price < 0.01) {
        msg = '请输入大于0的数字，最多保留两位小数'
      }
      if (price * 1 > stored * 1) {
        msg = '扣款金额不能大于储值余额'
      }
      if (msg) {
        this.$message.error(msg)
        return
      }

      this.$confirm(`请确认是否要扣款 [${price}元] ？`, this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.toConfirmEditDeduction({ id, price, content })
      })
    },
    async toConfirmEditDeduction (param) {
      let { code } = await this.$api.memberStaffDeduction(param)
      if (code === 200) {
        this.$message.success('扣款成功')
      }
      this.beforeClose()
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select,
.el-input {
  width: 200px;
}
</style>
